/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.view.template;

import offset.nodes.client.view.MappedSchemaNodeRenderer;
import offset.nodes.client.view.TreeNodeChooserDialog;
import java.awt.Dialog;
import java.net.URL;
import java.util.HashMap;
import javax.jcr.PropertyType;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import offset.nodes.Constants;
import offset.nodes.ResourceConstants;
import offset.nodes.client.chooser.view.TypeChooserDialog;
import offset.nodes.client.vdialog.model.template.AbstractTemplateNode;
import offset.nodes.client.model.HierarchyTree;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.vdialog.model.template.PathNode;
import offset.nodes.client.virtual.model.SchemaNode;
import offset.nodes.client.virtual.model.SchemaProperty;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.model.Server;
import offset.nodes.client.tree.model.TreeNodePanel;
import offset.nodes.client.tree.model.TreeNodePanelContainer;
import offset.nodes.client.model.TreeNodeUserObject;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.PropertyDefinition;
import offset.nodes.client.vdialog.model.template.NewTemplateConfiguration;
import offset.nodes.client.vdialog.model.template.PageNode;
import offset.nodes.client.tree.view.DetailPanelTreeConfiguratorPanel;
import offset.nodes.client.veditor.model.messages.TemplateEditorResult;
import offset.nodes.client.view.ResultState;

/**
 *
 * @author  Walter Lütgenau
 */
public class VirtualPagePanel extends javax.swing.JPanel implements TreeNodePanel {

    class TextFieldDocumentListener implements DocumentListener {

        public void changedUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void insertUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void removeUpdate(DocumentEvent e) {
            validateOkButton();
        }
    }
    TreeNodePanelContainer container = null;
    SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
    TypeChooserDialog newTypeChooser = null;
    Server server;
    TextFieldDocumentListener textFieldDocumentListener = new TextFieldDocumentListener();
    TreeNodeUserObject userObject;
    NodeTypes types = null;
    String pathNodeType;
    TemplateEditorResult representation = null;
    URL repository;

    /** Creates new form FolderPanel
     * @param server the server model
     * @param repository 
     * @param pathNodeType 
     */
    public VirtualPagePanel(Server server, URL repository, String pathNodeType) {
        this.server = server;
        this.pathNodeType = pathNodeType;
        this.repository = repository;
        initComponents();
    }

    public TreeNodePanelContainer getContainer() {
        return container;
    }

    public void setTypes(NodeTypes types) {
        this.types = types;
    }

    protected void validateExtendButton() {
        TreePath selected = container.getTree().getSelectionModel().getSelectionPath();
        if (selected == null)
            return;

        selected = selected.getParentPath();
        while (selected != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selected.getLastPathComponent();
            if (node.getParent() == null)
                break;

            AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
            if (userObject.getNodeType() != null) {
                extendButton.setEnabled(true);
                return;
            }

            selected = selected.getParentPath();
        }

        extendButton.setEnabled(false);
    }

    private void validateOkButton() {
        boolean ok = true;
        if (typeTextField.getText() == null || typeTextField.getText().length() == 0)
            editButton.setEnabled(false);
        else
            editButton.setEnabled(true);
        
        if (folderPropertyCombo.getItemCount() == 0)
            ok = false;

        container.enableOkButton(ok);
    }

    protected void setPath(PathNode definition) {
        if (definition.getQuery() != null) {
            typeTextField.setText(definition.getQuery());
            NodeTypeDefinition nodeTypeDefinition = types.get(QName.valueOf(namespaces.toQNameString(definition.getQuery())));
            if (nodeTypeDefinition != null)
                setProperties(nodeTypeDefinition.getDeclaredPropertyDefinitions(), definition.isResidual());

        } else
            typeTextField.setText("");

        if (definition.getNameProperty() != null) {
            folderPropertyCombo.setSelectedItem(definition.getNameProperty());
        }

        validateExtendButton();
        validateOkButton();
    }

    protected PageNode getPage() {
        PageNode page = (PageNode) userObject;

        page.setQuery(null);
        if (typeTextField.getText().length() > 0)
            page.setQuery(typeTextField.getText());

        page.setNameProperty((String) folderPropertyCombo.getSelectedItem());

        if (typeTextField.getText() != null && typeTextField.getText().length() > 0) {
            String path = page.getSchemaPath();
            int indexSeparator = path.indexOf("/");
            if (indexSeparator >= 0)
                path = path.substring(indexSeparator + 1);
            NodeTypeDefinition definition = types.get(QName.valueOf(namespaces.toQNameString(path)));
            page.setNodeType(definition);
        }

        if (representation != null)
            page.setPage(representation);

        return page;
    }

    protected void setProperties(PropertyDefinition[] properties, boolean isResidual) {
        folderPropertyCombo.removeAllItems();

        if (isResidual)
            folderPropertyCombo.addItem(QName.NAME_PROPERTY.getLocalName());

        for (int i = 0; i < properties.length; i++) {
            if (properties[i].getRequiredType() == PropertyType.NAME
                    || properties[i].getRequiredType() == PropertyType.UNDEFINED
                    || properties[i].getRequiredType() == PropertyType.PATH
                    || properties[i].getRequiredType() == PropertyType.STRING)
                folderPropertyCombo.addItem(namespaces.toPrefixName(properties[i].getName()));
        }
    }

    /**
     * Create an string array from the tree path
     * 
     * @param path The tree path
     * @return The string array
     */
    protected String[] toStringArray(TreePath path) {
        String[] names = new String[path.getPathCount()];
        int i = 0;
        while (path != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node.getUserObject() != null && node.getUserObject() instanceof AbstractTemplateNode) {
                AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
                names[i++] = userObject.getSchemaPath();
            }

            path = path.getParentPath();
        }

        return names;
    }

    /**
     * Determine the query string from the selected schema node
     * 
     * @param schema the schema nodes displayed to the user
     * @param selected the schema node selected by the user
     * @param mappedPathes a string array of pathnames of the parent nodes of the current virtual folder/page/template
     * @return the query string
     */
    protected String getExtendedPath(DefaultMutableTreeNode schema, DefaultMutableTreeNode selected, String[] mappedPathes) {
        StringBuffer result = new StringBuffer();
        StringBuffer path = new StringBuffer();

        while (schema != null) {
            if (path.length() > 0)
                path.append("/");
            path.append(schema.toString());
            boolean isMapped = false;

            for (int i = 0; i < mappedPathes.length; i++) {
                if (path.toString().equals(mappedPathes[i])) {
                    isMapped = true;
                    break;
                }
            }

            if (isMapped) {
                result = new StringBuffer(schema.toString());
                result.append("[ancestor()]");
            } else
                result.append("/" + schema.toString());

            if (schema == selected)
                break;

            if (schema.getChildCount() > 0)
                schema = (DefaultMutableTreeNode) schema.getChildAt(0);
            else
                schema = null;
        }

        return result.toString();
    }

    protected HashMap<String, String> createSecondaryQueryMap(String[] queries) {
        HashMap<String, String> result = new HashMap<String, String>();

        if (queries != null)
            for (int i = 0; i < queries.length; i++) {
                if (queries[i] == null || queries[i].length() == 0)
                    continue;
                String[] query = queries[i].split("=");
                result.put(query[0], query[1]);
            }

        return result;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        folderNameButtonGroup = new javax.swing.ButtonGroup();
        typeLabel = new javax.swing.JLabel();
        typeTextField = new javax.swing.JTextField();
        typeTextField.getDocument().addDocumentListener(textFieldDocumentListener);
        extendButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        namePathLabel = new javax.swing.JLabel();
        folderPropertyCombo = new javax.swing.JComboBox();
        editButton = new javax.swing.JButton();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/vdialog/view/DialogBundle"); // NOI18N
        typeLabel.setText(bundle.getString("template.templatePanel.query")); // NOI18N

        extendButton.setText(bundle.getString("template.templatePanel.extendQuery")); // NOI18N
        extendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectExtendedType(evt);
            }
        });

        newButton.setText(bundle.getString("template.templatePanel.newQuery")); // NOI18N
        newButton.setMaximumSize(new java.awt.Dimension(69, 23));
        newButton.setMinimumSize(new java.awt.Dimension(69, 23));
        newButton.setPreferredSize(new java.awt.Dimension(69, 23));
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectNewType(evt);
            }
        });

        namePathLabel.setText(bundle.getString("template.folderPanel.name")); // NOI18N

        folderPropertyCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        editButton.setText(bundle.getString("template.templatePanel.extendQuery")); // NOI18N
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editPage(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(editButton)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(typeLabel)
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(extendButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(typeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(namePathLabel)
                        .addGap(41, 41, 41)
                        .addComponent(folderPropertyCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(66, 66, 66))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(extendButton))
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(namePathLabel)
                    .addComponent(folderPropertyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addComponent(editButton)
                .addContainerGap(85, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    private void selectExtendedType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectExtendedType
        TreePath path = container.getTree().getSelectionModel().getSelectionPath();
        path = path.getParentPath();
        String[] mappedPathes = toStringArray(path);
        AbstractTemplateNode userObject = null;

        while (path != null) {
            DefaultMutableTreeNode current = (DefaultMutableTreeNode) path.getLastPathComponent();
            userObject = (AbstractTemplateNode) current.getUserObject();

            if (userObject == null)
                return;

            if (userObject.getQuery() != null && userObject.getQuery().indexOf("/") < 0)
                break;

            path = path.getParentPath();
        }

        DefaultMutableTreeNode querySchemaNode = HierarchyTree.setupHierarchicalTree(userObject.getNodeType().getName(), userObject.getNodeType(), null, types, false, false);
        TreeNodeChooserDialog chooser = new TreeNodeChooserDialog(null, true, querySchemaNode);
        chooser.setCellRenderer(new MappedSchemaNodeRenderer(mappedPathes));
        chooser.setVisible(true);
        if (chooser.getReturnStatus() == TreeNodeChooserDialog.RET_OK) {
            DefaultMutableTreeNode selected = chooser.getSelectedNode();

            boolean isResidual = false;
            for (int i = 0; i < selected.getChildCount(); i++) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) selected.getChildAt(i);
                if (child.getUserObject() instanceof SchemaProperty) {
                    SchemaProperty property = (SchemaProperty) child.getUserObject();
                    if (property.getName().equals(QName.NAME_PROPERTY))
                        isResidual = true;
                }
            }
            typeTextField.setText(getExtendedPath(querySchemaNode, selected, mappedPathes));
            NodeTypeDefinition definition = ((SchemaNode) selected.getUserObject()).getNodeType();
            ((PathNode) userObject).setResidual(isResidual);
            setProperties(definition.getDeclaredPropertyDefinitions(), isResidual);
        }

}//GEN-LAST:event_selectExtendedType

    private void selectNewType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectNewType
        if (newTypeChooser == null)
            newTypeChooser = new TypeChooserDialog(null, true,
                    types.getArray(new QName[]{new QName(Constants.URI_NODES_DATA, ""), new QName(Constants.URI_NODES, "")}));
        newTypeChooser.setVisible(true);
        if (newTypeChooser.getReturnStatus() == TypeChooserDialog.RET_OK) {
            typeTextField.setText(namespaces.toPrefixName(newTypeChooser.getDefinition().getName()));
            /**
             * A new type will store its data nodes in a node of nt:unstructured, hence it will have a residual name itself
             */
            ((PathNode) userObject).setResidual(true);
            setProperties(newTypeChooser.getDefinition().getDeclaredPropertyDefinitions(), true);

            validateOkButton();
        }
}//GEN-LAST:event_selectNewType

    private void editPage(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editPage
        String typeName = typeTextField.getText();
        int separator = typeName.lastIndexOf("/");
        if (separator >= 0)
            typeName = typeName.substring(separator + 1);

        String html = "<html><head><link type='text/css' rel='stylesheet' href='"
                + repository + ResourceConstants.MAIN_APPLET_CSS
                + "'/></head><body><div n-schema=\""
                + typeName + "\" n-data=\""
                + typeName + "\"><p/></div></body></html>";

        if (representation != null)
            html = representation.getSampleHtml();
        try {
            EditorDialog dialog = null;
            String templatePath = ((NewTemplateConfiguration) ((DetailPanelTreeConfiguratorPanel) getContainer()).getTreeModel()).getTemplatePath();
            if (representation != null)
                dialog = new EditorDialog((Dialog) null, true, html, types, server.getURL(), repository,
                        createSecondaryQueryMap(representation.getSecondaryQueries()), templatePath);
            else
                dialog = new EditorDialog((Dialog) null, true, html, types, server.getURL(), repository,
                        null, templatePath);
            if (dialog.getReturnCode() == ResultState.Success)
                representation = dialog.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_editPage
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton editButton;
    private javax.swing.JButton extendButton;
    private javax.swing.ButtonGroup folderNameButtonGroup;
    private javax.swing.JComboBox folderPropertyCombo;
    private javax.swing.JLabel namePathLabel;
    private javax.swing.JButton newButton;
    private javax.swing.JLabel typeLabel;
    private javax.swing.JTextField typeTextField;
    // End of variables declaration//GEN-END:variables

    public void setPanel(TreeNodeUserObject userObject) {
        this.userObject = userObject;
        if (userObject != null && userObject instanceof PathNode)
            setPath((PathNode) userObject);

        if (userObject != null && userObject instanceof PageNode) {
            PageNode page = (PageNode) userObject;
            representation = page.getPage();
        }
    }

    public TreeNodeUserObject getUserObject() {
        return getPage();
    }

    public void setContainer(TreeNodePanelContainer container) {
        this.container = container;
    }
}
